<?
// различные функции, которые используются при каждом или почти каждом запросе
// остальные утилиты - в misc.php



function p($label)
{
	if($_GET['debug'])	Profiler::next($label);
}

function pstart($label)
{
	if($_GET['debug'])  Profiler::start($label);
}

function pstop($label='')
{
	if($_GET['debug'])  Profiler::stop($label);
}



function getWeekDay($dt=0)
{
	if($dt==0) $dt=time();
	$wd = date("w",$dt);
	if($wd==0) return 7;
	else return $wd;
}


function getUploadExtension($field_name)
{
	if(!is_uploaded_file($_FILES[$field_name]['tmp_name'])) return false;
	return strtolower(end(explode( ".", $_FILES[$field_name]['name'] )));
}


function implode2($arr, $default='0')
{
	$str = implode(',', $arr);
	if(!$str) $str = $default;
	return $str;
}


function array2json($i=array()) 
{
	$o='';
	foreach ($i as $k=>$v){
		if(is_array($v))
		{
			$o .= '"'.$k.'":'.array2json($v).',';
		}
		else
		{
			$v = str_replace("\\","\\\\",$v);
			$o .= '"'.$k.'":"'.str_replace('"','\"',$v).'",';
		}
	}
	$json = '({'.substr($o,0,-1).'})';
	$json = str_replace("\n",'\n',$json);
	$json = str_replace("\r",'',$json);
	return $json;
}


function from1251($str)
{
	return iconv('Windows-1251','UTF-8',$str);
}

function to1251($str)
{
	return iconv('UTF-8','windows-1251//IGNORE//TRANSLIT',$str);
}

function get_user_cookie_hash($userid)
{
	$hash = DB::scalarSelect("select hash from usercookie where userid={$userid}");
	if(!$hash)
	{
		$hash = md5($userid.time().microtime(true));
		$hash = substr($hash,0,16);
		DB::query("insert into usercookie (userid,hash,enters) values (?i,?,?i)", $userid, $hash, 0);
	}
	return $hash;
}

function link_user_cookies($id1, $id2)
{
	$new_id = $id1;
	$min_id = min($id1, $id2);
	$max_id = max($id1, $id2);
	
	$rowid = DB::scalarSelect("select id from uc_set where min_id={$min_id} and max_id={$max_id}");
	if($rowid)
	{
		$last_id = DB::scalarSelect("select last_id from uc_set where id=".$rowid);
		if($last_id!=$new_id)
		{
			DB::query("update uc_set set last_id={$new_id}, enters = enters+1 where id=".$rowid);
		}
	}
	else
	{
		DB::query("insert into uc_set (min_id,max_id,enters,last_id) values ({$min_id},{$max_id},1,{$new_id})");
		$profile1 = Model_Profile::load($id1);
		$profile2 = Model_Profile::load($id2);
		if($profile1->id && $profile2->id)
		{
			alert_log($id2,$id1,' '.$profile1->getLinkWithIcon().'    '.$profile2->getLinkWithIcon());
		}
	}
}




function doc_comment_log($docid,$userid)
{
  $id = DB::scalarSelect("select id from doc_comments where documentid={$docid}");
  if($id)
  {
    DB::query("update doc_comments set dt=".time().", userid={$userid} where id=".$id);
  }
  else
  {
    DB::query("insert into doc_comments (documentid,userid,dt) values ({$docid},{$userid},".time().")");
  }
}


function alert_log($docid,$userid,$message)
{
  $count = DB::scalarSelect("select count(*) from alert_log where documentid={$docid} and userid={$userid}");
  if($count==0)
  {
    DB::query("insert into alert_log (documentid,userid,dt,message)
                values (?i, ?i, ?i, ?)",
								$docid, $userid, time(), $message);
  }
}


function isCrawler()
{
	if(isset($_SESSION['current_user'])) return false;
	
	$ua = strtolower($_SERVER["HTTP_USER_AGENT"]);
	
	// sputnik - mail.ru browser bar
	// chrome
	// windows nt - windows
	if( is_int(strpos($ua,'windows nt')) 
			|| is_int(strpos($ua,'chrome')) 
			|| is_int(strpos($ua,'sputnik')) 
	) return false;
	
	// spiders
	if (
    	   is_int(strpos($ua,'yandex'))
				|| is_int(strpos($ua,'connect'))
				|| is_int(strpos($ua,'mailru'))
				|| is_int(strpos($ua,'rambler'))
				|| is_int(strpos($ua,'spyder'))
				|| is_int(strpos($ua,'spider'))
				|| is_int(strpos($ua,'bot'))
				|| is_int(strpos($ua,'msnbot'))
				|| is_int(strpos($ua,'yahoo'))
				|| is_int(strpos($ua,'slurp'))
				|| is_int(strpos($ua,'mail.ru'))
				|| is_int(strpos($ua,'nigma.ru'))
				|| is_int(strpos($ua,'crawler'))
				|| (is_int(strpos($ua,'google')) && !is_int(strpos($ua,'chrome'))  )
	)
	return true;
	else
	return false;
}


function inner_trim($tex)
{
	while(is_int(strpos($tex,'  ')))
	{
		$tex = str_replace('  ',' ',$tex);
	}
	return $tex;
}

/*
function d($some)
{
	if(!isset($_GET['debug'])) return;
	if(is_array($some) || is_object($some)) 
		print_r($some);
	else
		echo $some;
}
*/

function d($mParam, $bExit = 0, $bVarDump = 0)
{
    echo '<hr><pre>';
    if (!$bVarDump)
    {
        print_r($mParam);
    }
    else
    {
        var_dump($mParam);
    }
    echo '</pre><hr>';
    if ($bExit) exit;
}

function censor_text($text, $is_admin = false)
{
	$censors = $GLOBALS["censors"];
  
	if(strlen($text)>500000) return $text;
	
	if(sizeof($censors))
	{
    if($is_admin)
      $text = preg_replace($censors['match'], $censors['replace_admin'], $text);
    else
    	$text = preg_replace($censors['match'], $censors['replace'], $text);
	}
  
	return $text;
}





function getRegionId($title)
{
	global $allregions;
	foreach($allregions as $v)
	{
		if($v['title']==$title) return $v['id'];
	}
	return 0;
}


function getRegionById($id)
{
	global $allregions;
	foreach($allregions as $v)
	{
		if($v['id']==$id) return $v;
	}
	return false;
}


function getUserCityId($title, $regionid)
{
	if(!$title) return 0;
	
	$id = DB::scalarSelect("select id from city where title=? and regionid=?i", $title, $regionid);
	if($id) return $id;
	
	$geoid = intval( DB::scalarSelect("select id from city_geo where title=?", $title) );
	$id = DB::insert("city", Array("title"=>$title, "regionid"=>$regionid, "geoid"=>$geoid ));
	return $id;
}


function cityInfo()
{
	$ip = sprintf("%u", ip2long($_SERVER['REMOTE_ADDR']) );
	$rows = DB::getRows("select * from city_ip where ip_min<={$ip} and ip_max>={$ip}");
	$minrow=Array("gorod"=>false,"width"=>10000000);	
	foreach($rows as $row)
	{
		if($row['width'] < $minrow['width'] )  $minrow=$row;
	}
	if($minrow['gorod']) 
		return $minrow;
	else
		return false;
}


function countryInfo()
{
	$ip = sprintf("%u", ip2long($_SERVER['REMOTE_ADDR']) );
	$rows = DB::getRows("select countryid,width from country_ip where ip_min<={$ip} and ip_max>={$ip}");
	$minrow=Array("countryid"=>0, "width"=>10000000);	
	foreach($rows as $row)
	{
		if($row['width'] < $minrow['width'] )  $minrow=$row;
	}
	
	return DB::singleRow("select * from country where id=".$minrow["countryid"]);
}






function getFilename()
{
	DB::query('insert into `filenames` (foo) values (1)');
	$id = DB::getInsertId();
	DB::query('delete from `filenames` where id<'.$id);
	
	// example: 2009sep/12/57/12345_12345
	$str = date('Y').strtolower(date('M')) . '/' . date('d') . '/' . date('i') . '/'. $id.'_'.rand(10000,99999);
	return $str;
}


function prepareOutput($response)
{
	//pstart($_SERVER['REQUEST_URI']);
	//$response = str_replace('<img ','<img border=0 ',$response );
	//$response = str_replace(' src="/',' src="http://'.HOST_NAME.'/',$response );
	//$response = str_replace(' href="/',' href="http://'.HOST_NAME.'/',$response );
	//pstop();  
	
  //$is_admin = (isset($_SESSION['current_user']) && $_SESSION['current_user']->isAdmin());
  //$response = censor_text($response, $is_admin);
	
	return $response;
}


function metaStrip($tex)
{
	$tex = strip_tags($tex);
	$tex = str_replace("\r",'',$tex);
	$tex = str_replace("\n",' ',$tex);
	$tex = str_replace('"','&quot;',$tex);
	return $tex;
}


function rus2lat($str)
{
	$rus = array('ё','ж','ц','ч','ш','щ','ю','я','Ё','Ж','Ц','Ч','Ш','Щ','Ю','Я','Ъ','Ь','ъ','ь');
	$lat = array('e','zh','c','ch','sh','sh','ju','ja','E','ZH','C','CH','SH','SH','JU','JA','','','','');
	$str = str_replace($rus,$lat,$str);
	$str = strtr($str,
	    "АБВГДЕЗИЙКЛМНОПРСТУФХЫЭабвгдезийклмнопрстуфхыэ",
	    "ABVGDEZIJKLMNOPRSTUFHIEabvgdezijklmnoprstufhie");
		return($str);
}


function setSelfUrl()
{
	global $selfurl;
	
	$selfurl = $_SERVER['REQUEST_URI'];

	if (is_int(strpos($selfurl, '/login'))
	    || is_int(strpos($selfurl, '/remind'))
	    || is_int(strpos($selfurl, '/signup'))
 	    || is_int(strpos($selfurl, '/logout'))
	    || is_int(strpos($selfurl, '/activate'))
	    || is_int(strpos($selfurl, '/submit'))
	    || is_int(strpos($selfurl, '/delete'))
	){
	   $selfurl = '/';
	}
	
	if ($selfurl != '/')
	{
	    $selfurl = 'http://'.$_SERVER['HTTP_HOST'].$selfurl;
	}
	
	if (isset($_REQUEST['backurl']))
	{
	    $selfurl = $_REQUEST['backurl'];
	}
}

// extravert
function setCurrentUrl()
{
    global $cururl;
    $cururl = $_SERVER['REQUEST_URI'];
}

function queryBuilder($params=null,$prepare=false,$page="")
{
	if($page=="")
	{
		$page = substr($_SERVER["REQUEST_URI"],1);
		$page = str_replace("admin/","",$page);
	}
	if($params)	
	{
		$ps = explode("&", $params);
		if(!is_array($ps)) $ps=Array($ps);
		foreach($ps as $param){
			list($pname,$pval) = explode("=", $param);
			$page = str_replace("&".$pname."=".$_GET[$pname],"",$page);
			$page = str_replace("?".$pname."=".$_GET[$pname],"?",$page);
		}
		if( !is_int( strpos($page,"?") ) ) $page.="?";
		foreach($ps as $param){
			list($pname,$pval) = explode("=", $param);
			if($pval){
				$sep="";
				if( $page[strlen($page)-1]!="&" &&  $page[strlen($page)-1]!="?") $sep="&";
				$page.=$sep.$pname."=".$pval;
				}
			}
		}
	if($prepare)
	{
		if( is_int( strpos($page,"?") ) && $page[strlen($page)-1]!="?" && $page[strlen($page)-1]!="&") $page.="&";
		if( !is_int( strpos($page,"?")) ) $page.="?";
		}
	else
	{
		if( $page[strlen($page)-1]=="&" ) $page=substr($page,0,strlen($page)-1);
		if( $page[strlen($page)-1]=="?" ) $page=substr($page,0,strlen($page)-1);
	}
	$page=str_replace('?&','?',$page);
	
	if(strlen($page)>5 && substr($page,0,5)=='http:')
		return $page;
	else
		return 'http://'.$_SERVER['HTTP_HOST'].'/'.$page;
}

function urlMapping()
{
	global $CONFIG;
	$uri = $_SERVER['REQUEST_URI'];

	if (is_int(strpos($uri, '?')))
	{
		$uri = substr($uri, 0, strpos($uri, '?'));
	}
	$uri = trim(strtolower($uri), ' /');

	$sController = $sMethod = '';
	$aParts = explode('/', $uri);

    if (!$uri)
    {
        $sControl = $CONFIG['url-mapper']['default'];
        return array($sControl, array());
    }

//d($aParts, 1);
	if (isset($aParts[2]) && method_exists('Controller_'.ucfirst($aParts[0]).'_'.ucfirst($aParts[1]), $aParts[2]))
	{
	    $sController = ucfirst($aParts[0]).'_'.ucfirst($aParts[1]);
        $sMethod = $aParts[2];
        $aParams = array_slice($aParts, 3);
	}
	elseif (isset($aParts[1]) && class_exists('Controller_'.ucfirst($aParts[0]).'_'.ucfirst($aParts[1])))
	{
        $sController = ucfirst($aParts[0]).'_'.ucfirst($aParts[1]);
        $sMethod = 'index';
        $aParams = array_slice($aParts, 2);
	}
    elseif (class_exists('Controller_'.ucfirst($aParts[0]).'_Home'))
    {
        $sController = ucfirst($aParts[0]).'_Home';
        $sMethod = 'index';
        $aParams = array_slice($aParts, 1);
    }
    elseif (method_exists('Controller_Main', $aParts[0]))
    {
        $sController = 'Main';
        $sMethod = $aParts[0];
        $aParams = array_slice($aParts, 1);
    }
	
	if ($sController && $sMethod)
	{
	    return array('Controller_'.$sController.'.'.$sMethod, $aParams);
	}
	else
	{
	    return;
    	$max=0;
    	$match='';
    	foreach ($CONFIG['url-mapper'] as $k => $v)
    	{
    		if (strpos($uri, $k) === 0
    		    && strlen($k) > $max
    		    && (strlen($k) == strlen($uri)
    		        || $uri[strlen($k)] == '?'
    		        || $uri[strlen($k)] == '/')
	        ){
    			$match = $v;
    			$max = strlen($k);
    		}
    	}
    	if(!$match) 
    	{
    		$surl = $uri;
    		if ($surl[strlen($surl) - 1] == '/')
    		{
    		    $surl = substr($surl, 0, strlen($surl) - 1);
    		}
    		
    		return array($CONFIG['url-mapper']['404'], Array($uri));
    	}
    	
    	$uri = substr($uri, $max);
    	if ($uri[strlen($uri)-1] == '/')
    	{
    	    $uri = substr($uri, 0, strlen($uri) - 1);
    	}
    	$params = explode('/', $uri);
    	
    	return array($match, $params);
	}
}




function getSpart()
{
	$cu = getCurrentUser();
	if (!$cu) return '';
	// extravert
	$id = is_object($cu) ? $cu->id : $cu['id'];
	return substr(md5($id), 4, 5);
}


function checkSpart($ret = false)
{
	$str = getSpart();
	if($str && ($_GET['spart']==$str || $_POST['spart']==$str) ) return true;
	
	if($ret) return false;
	else
	{
		echo '<b>Ошибка!</b><br><br>Что-то пошло не так. Пожалуйста, войдите на сайт снова и попробуйте повторить действие.<br><br><a href="/">Войти на сайт</a>';
		exit;
	}
}




function ajax($str)
{
	echo $str;
	exit;
}


function Redirect2($url)
{
	$view = new View();
	$view->add("url", $url);
	$view->template = 'service/redirect.tpl';
	echo $view->render();
	exit;
}


function Redirect($url)
{
	if (!is_int(strpos($url, 'http')))
	{
	    $url = 'http://'.HOST_NAME.$url;
	}
	header("Location: $url");
	exit;
}

function RedirectMobile($url)
{
	if(!is_int(strpos($url,'http'))) $url = 'http://m.'.HOST_NAME_SHORT.$url;
	header("Location: $url");
	exit;
}


function setCurrentUser($profile)
{
	begin_session();
	$_SESSION["current_user"] = $profile;
}


function hasCurrentUser()
{
	return isset($_SESSION['current_user']);
}

function getCurrentUser()
{
	if (!isset($_SESSION['current_user'])) return false;
	return $_SESSION['current_user'];
}


function needCurrentUser()
{
		global $selfurl;
		if(!isset($_SESSION['current_user'])) 
		{
			Redirect('/login?backurl='.$selfurl);
		}
		return $_SESSION['current_user'];
}

function needCurrentUserMobile()
{
		global $selfurl;
		if(!isset($_SESSION['current_user'])) 
		{
			RedirectMobile('/login?backurl='.$selfurl);
		}
		return $_SESSION['current_user'];
}


function prepareBB($bb)
{
	$bb = str_replace("&nbsp;"," ", $bb);
	$bb = str_replace("[img][img]","[img]", $bb);
	$bb = str_replace("[/img][/img]","[/img]", $bb);
	
	// убираем недоступные юзеру смайлы
	$bb = smileReplace($bb);
	
	$bb = trim($bb);
	$bb = inner_trim($bb);
	
	$obj = new bbcode($bb);
	$text = $obj->get_html();
	
	$bb = str_replace("'","&rsquo;",$bb);
  $text = str_replace("'","&rsquo;",$text);
	$text = str_replace("&amp;","&", $text);
	$text = str_replace("&nbsp;"," ", $text);
	return array($bb, $text);
}


function smileReplace($bb)
{
	$cu = getCurrentUser();
	if(!$cu || isset($_SESSION["userdata"])) return $bb;
	
	if(!$cu->canSeeSmile(2))
	{
		$arr = Array('x18','x20','x21','x15','x25','13','8','x22','d1','d3');
		foreach($arr as $fn)
		{
			$bb = str_replace('/i/smiles/'.$fn.'.gif', '/i/smiles/no.gif', $bb);
		}
		$arr = Array('saint', 'evil', 'cryriver' ,'beach' ,'cake', 'drink', 'shock', 'sleep', 'beee', 'dance');
		foreach($arr as $a)
		{
			$bb = str_replace(':'.$a.':', '', $bb);
		}
	}
	
	if(!$cu->canSeeSmile(3))
	{
		$arr = Array('n11','n6','n3','n5','5','n10','d5','d4','d7','d10','n15');
		foreach($arr as $fn)
		{
			$bb = str_replace('/i/smiles/'.$fn.'.gif', '/i/smiles/no.gif', $bb);
		}
		$arr = Array('dontknow', 'bravo', 'sorry' ,'goodluck' ,'yahoo', 'sport', 'popcorn', 'running', 'no', 'bye');
		foreach($arr as $a)
		{
			$bb = str_replace(':'.$a.':', '', $bb);
		}
		$bb = str_replace(':-p', ':p', $bb);
	}
	
	
	$arr1 = Array('n1','d9','x10','n4','d2','n8','n2','n13');
	$arr2 = Array('help', 'nails', 'cloud', 'flowers' ,'med' ,'champ', 'wall', 'supermama');
	for($i=0;$i<8;$i++)
	{
		if(!$cu->canSeeSmile(4,$i+1))
		{
			$bb = str_replace('/i/smiles/'.$arr1[$i].'.gif', '/i/smiles/no.gif', $bb);
			$bb = str_replace(':'.$arr2[$i].':', '', $bb);
		}
	}
	
	$bb = str_replace('[img]http://'.HOST_NAME.'/i/smiles/no.gif[/img]', '', $bb);
	$bb = str_replace('[IMG]http://'.HOST_NAME.'/i/smiles/no.gif[/IMG]', '', $bb);
	$bb = str_replace('http://'.HOST_NAME.'/i/smiles/no.gif', '', $bb);
	
	return $bb;
}





function divideWords($str, $maxlength=30)
{
	// разбиваем слишком длинные слова
	// ОСТОРОЖНО! ТЕГИ!
  return wordwrap($str, $maxlength, ' ', 1);
}



function isPoetry($content)
{
	$count_images = substr_count($content, '<img') - substr_count($content, 'smiles');
	$count_video  = substr_count($content, '<rutube ') + substr_count($content, '<youtube ');
	if($count_images>5) return false;
	
	$content = str_replace("\r",'',$content);
	$content = str_replace("\n",'',$content);
	$content = str_replace('<br />','<br>',$content);
	$content = strip_tags($content,'<br>');
	$content = str_replace('<br>',"\n",$content);
	
	// слишком большой текст - явно не стих
	if(strlen($content)>30000) return false;
	
	$lcount = substr_count($content, "\n");
	// если мало строк нас это не касается, даже если там стихи
	if( $lcount<4 ) return false;
	
	if($count_video)
	{
		 if( $lcount<10 ) return false;
	}
	
	// если все строки длинные - не стихи
	$avg = strlen($content) / $lcount;	
	if($avg>50) return false;
	
	// если строки короткие, надо выяснить, не слишком ли коротки отдельные, вдруг они вообще пустые
	$lines = explode("\n", $content);
	$sum_normal   = 0;
	$count_normal = 0;
	$count_short  = 0;
	$count_long   = 0;
	$count_all    = 0;
	foreach($lines as $line)
	{
		if( strlen($line)<2 )  {continue;}
		if( strlen($line)<10 ) {$count_short++;continue;}
		if( strlen($line)>80 ) {$count_long++;continue;}
		
		$sum_normal   += strlen($line);
		$count_normal++;
	}
	$count_all = $count_normal + $count_short + $count_long;
	
	// если строки нужной нам длины составляют менее 80% всех строк - не стихи
	if( $count_normal < 0.8 * $count_all ) return false;
	
	return true;
}



function Annotate($content, $prefered_length, $url='', $extrainfo=true)
{
	  // считаем сколько картинок и видео в тексте
		if($extrainfo)
		{
			$count_images = substr_count($content, '<img') - substr_count($content, 'smiles');
			$count_video  = substr_count($content, '<rutube ') + substr_count($content, '<youtube ');
		}
		
		$content = strip_tags($content,'<br>');
		$content = str_replace("\r",'',$content);
		$content = str_replace("\n",'',$content);
		$content = str_replace("\t",' ',$content);
		$content = str_replace('<br />','<br>',$content);
		$content = str_replace('<br>&nbsp;<br>','<br>',$content);
		$content = preg_replace('/<br>\s+/','<br>',$content);
		$content = preg_replace('/\s+<br>\s+/','<br>',$content);
		for($i=0;$i<10;$i++)
		{
			$content = str_replace('<br><br>','<br>',$content);
		}
		while(is_int(strpos($content,'<br><br>'))) 
		{
			$content = str_replace('<br><br>','<br>',$content);
		}
		if(strpos($content,'<br>')===0) $content = substr($content,4);
		
		if($prefered_length > 0 && strlen($content) < $prefered_length) 
		{
			// добавим инфу про фото и видео
			$div_more = false;
			if(($count_images>0 || $count_video>0) && strlen($content)>10) $div_more = true;
			
			if($div_more)
			{
				$content = '<div>'.$content.'</div>';
				$content.='<div class="more_more">';
			}
			if($count_images>0)
			{
				$content.='<a href="'.$url.'" class="more_photo">'.$count_images.' фото'.pluralForm($count_images,'графия','графии','графий').'</a>';
			}
			if($count_video>0)
			{
				$content.='<a href="'.$url.'" class="more_video">'.$count_video.' видео'.pluralForm($count_video,'ролик','ролика','роликов').'</a>';
			}
			if($div_more)
			{
					$content.='</div>';
			}
			return $content;
		}
		
		if(($prefered_length == 0) || (strlen($content) < $prefered_length)) {
			return $content;
		}
		
		$annotation = $content;
		$content = substr($content,0, $prefered_length);
		$pos1 = strrpos($content,'. ')+1;
		$pos2 = strrpos($content,".\r")+1;
		$pos3 = strrpos($content,".\n")+1;
		$pos4 = strrpos($content,'!')+1;
		$pos5 = strrpos($content,'?')+1;
		$pos6 = strrpos($content,' ')+1;		
		$pos6 = strrpos($content,'<br>');
		if($pos1>1 || $pos2>1 || $pos3>1 || $pos4>1 || $pos5>1 || $pos6>1 || $pos7>1)
		{
			$pos = max($pos1,$pos2, $pos3,$pos4,$pos5,$pos6, $pos7);
			$content = substr($content,0, $pos);
		}
		else
		{
			$separator = md5(time());
			$a = wordwrap($annotation, $prefered_length, "[$separator]");
			
			$content = substr($annotation, 0, strpos($a, "[$separator]"));
		}
		
		if($extrainfo)
		{
			$content.=' <a href="'.$url.'" class="more"><span>Читать&nbsp;далее</span>&raquo;</a>';
		}
		
		// добавим инфу про фото и видео
		$div_more = false;
		if(($count_images>1 || $count_video>0) && strlen($content)>10) $div_more = true;
		
		if($div_more)
		{
			$content = '<div>'.$content.'</div>';
			$content.='<div class="more_more">';
		}
		if($count_images>1)
		{
			$content.='<a href="'.$url.'" class="more_photo">'.$count_images.' фото'.pluralForm($count_images,'графия','графии','графий').'</a>';
		}
		if($count_video>0)
		{
			$content.='<a href="'.$url.'" class="more_video">'.$count_video.' видео'.pluralForm($count_video,'ролик','ролика','роликов').'</a>';
		}
		if($div_more)
		{
				$content.='</div>';
		}
		
		return $content;
}


function random_array($size, $max, $min = 0)
{
    $result = array();
    if ($size > $max + 1)
        $size = $max + 1;
    for ($i = 0; $i < $size; $i++) {
        for ($j = 0; $j < 100; $j++)
            {
            $rand = rand($min, $max);
            if (!in_array($rand, $result))
                break;
        }
        $result[] = $rand;
    }
    return $result;
}


function instr($str, $substr)
{
	return is_int( strpos($str,$substr) );
}


function addCrumb($title,$url='')
{
	if($url && substr($url,0,7)!='http://' ) $url = 'http://'.HOST_NAME.$url;
	if($url) $GLOBALS['crumbs'][] = Array('title'=>$title,'url'=>$url);
}


function begin_session()
{
	if( !isset( $_SESSION ) && !$_REQUEST[session_name()]) 
	{
		my_start_session();
	}
}

function my_start_session()
{
	if(!isset($_COOKIE[session_name()]))
	{
		session_id( md5(rand(0, 999999).$_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT'].microtime(false)) );
	}
	
	session_start();
	setcookie(session_name(), session_id(), time() + 10*86400, "/", '.'.HOST_NAME_SHORT);
}


function pluralForm($n, $form1, $form2, $form5)
  {
    $n = abs($n) % 100;
    $n1 = $n % 10;
    if ($n > 10 && $n < 20) return $form5;
    if ($n1 > 1 && $n1 < 5) return $form2;
    if ($n1 == 1) return $form1;
    return $form5;
  }


function rusdate2int($txt)
{
	if(!$txt) return 0;
	list($day,$month,$year) = explode('.',$txt);
	if(strlen($day)<2) $day='0'.$day;
	if(strlen($month)<2) $month='0'.$month;
	return strtotime($year.'-'.$month.'-'.$day);
}


function int2rusdate($dt)
{
	return date("d.m.Y",$dt);
} 

function getClassNameById($classid)
{
	global $CONFIG;
	foreach($CONFIG['classid'] as $k=>$v)
	{
		if($v==$classid) return $k;
	}
	return 'document';
}



function checkdateRus($dt)
{
	$arr = explode('.',$dt);
	if(sizeof($arr)!=3) return false;
	
	$day=intval($arr[0]);
	$month=intval($arr[1]);
	$year=intval($arr[2]);
	
	return checkdate($month,$day,$year);
}


function tm($mes='',$restart=false)
{
	global $st;
	echo (microtime(true)-$st)." $mes <br>";
	if($restart) $st=microtime(true);
}



function safe_glob($pattern, $flags=0) 
{
    $split=explode('/',$pattern);
    $match=array_pop($split);
    $path=implode('/',$split);
    if (($dir=opendir($path))!==false) {
        $glob=array();
        while(($file=readdir($dir))!==false) {
            if (fnmatch($match,$file)) {
                if ((is_dir("$path/$file"))||(!($flags&GLOB_ONLYDIR))) {
                    if ($flags&GLOB_MARK) $file.='/';
                    $glob[]=$path.'/'.$file;
                }
            }
        }
        closedir($dir);
        if (!($flags&GLOB_NOSORT)) sort($glob);
        return $glob;
    } else {
        return false;
    }
}

if (!function_exists('fnmatch')) 
{
    function fnmatch($pattern, $string) 
		{
        return @preg_match('/^' . strtr(addcslashes($pattern, '\\.+^$(){}=!<>|'), array('*' => '.*', '?' => '.?')) . '$/i', $string);
    }
}